#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"
#include "InerAddr.hpp"

using namespace LogModule;
const std::string defaultdict = "./dictionary.txt";
const std::string sep = ": ";

class Dict
{
public: 
    Dict(const std::string &path = defaultdict) :_dict_path(path)
    {}

    bool LoadDict()
    {
        std::ifstream in(_dict_path);
        if (!in.is_open())
        {
            LOG(LogLevel::ERROR) << "字典文件打开失败 " << _dict_path;
            return false;
        }
        std::string line;
        while (std::getline(in, line))
        {
            auto pos = line.find(sep);
            if(pos == std::string::npos)
            {
                LOG(LogLevel::WARNING) << "解析: " << line << "失败";
                continue;
            }
            std::string english = line.substr(0, pos);
            std::string chinese = line.substr(pos + sep.size());
            _dict[english] = chinese;
        }
        return true;
    }
    
    std::string Translate(const std::string& word, const InerAddr& client)
    {
        auto it = _dict.find(word);
        if(it == _dict.end())
        {
            return "None";
        }
        LOG(LogLevel::DEBUG) << "进入了翻译模块, " << client.Ip() << " : " << client.Port() << " : " << word << " -> " << it->second;

        return it->second;
    }

    ~Dict()
    {

    }
private:
    std::string _dict_path;
    std::unordered_map<std::string, std::string> _dict;
};